package com.boot2.core.web.websocket;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.boot2.core.model.vo.Result;
import lombok.SneakyThrows;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.GenericMessage;

/**
 * @author zhangweilin
 * @Description: 将服务端推送的消息，自动转换成和http接口返回的一样
 * @date 2020/7/23
 */
public class ResultChannelInterceptor implements ChannelInterceptor {
    @SneakyThrows
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        Object payload = message.getPayload();
        if (payload instanceof Result) {
            String json = JSONObject.toJSONString(payload, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat);
            if (message instanceof GenericMessage) {
                GenericMessage<byte[]> genericMessage = new GenericMessage<>(json.getBytes("UTF-8"), message.getHeaders());
                message = genericMessage;
            }
        }
        return message;
    }

}
